package com.bwsoft.portal.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.domain.DictionaryData;
import com.bwsoft.portal.service.IndexPageService;
import com.bwsoft.util.MD5Util;

@Service(IndexPageService.NAME)
public class indexPageServiceImpl extends PortalBaseServiceImpl implements
		IndexPageService {
	private static Logger LOG = Logger.getLogger(indexPageServiceImpl.class);

	@Override
	public ResponsePojo findAccount(String account, String password) {
		request = ServletActionContext.getRequest();
		session = request.getSession();
		ResponsePojo rp = new ResponsePojo();
		try {

			String checkUserHql="from Account as ac where ac.account=?";
			
			List<Account> accounts=accountDao.findByHql(checkUserHql, account);
			
			if(accounts.size()==0){
				rp.setErrcode(1);
				rp.setErrmsg("没有此账号！");
				return rp;
			}
			Account acc=new Account();
			//通过Account acc=accounts.get(0);获取的acc有时候取不到部分属性值
			//保存属性值其实没有必要，只需要把id放入session中
			acc.setAccountId(accounts.get(0).getAccountId());
			acc.setPassword(accounts.get(0).getPassword());
			acc.setAccountType(accounts.get(0).getAccountType());
			acc.setAddress(accounts.get(0).getAddress());
			acc.setHeadImgURL(accounts.get(0).getHeadImgURL());
			acc.setNickName(accounts.get(0).getNickName());
			acc.setSex(accounts.get(0).getSex());
			acc.setBirthday(accounts.get(0).getBirthday());
			acc.setPhone(accounts.get(0).getPhone());
			acc.setCompName(accounts.get(0).getCompName());
			acc.setCompNature(accounts.get(0).getCompNature());
			acc.setEmail(accounts.get(0).getEmail());
			acc.setLinkMan(accounts.get(0).getLinkMan());
			acc.setFax(accounts.get(0).getFax());
			if (acc.getCompNature() != null &&!"".equals(acc.getCompNature())) {
				List<DictionaryData> dicDatas = dictionaryDataDao.findByHql(
						"from DictionaryData dic where dic.dictionary.dicName='comp_nature' and dic.dicKey='" + acc.getCompNature() + "'");
				DictionaryData dicData = (DictionaryData)dicDatas.get(0);
				acc.setCompNatureName(dicData.getDicValue());
			}
			if(null!=acc.getJinyongFlag()&&acc.getJinyongFlag()){
				rp.setErrcode(1);
				rp.setErrmsg("该账号已经被禁用！");
				return rp;
			}
			
			String pwd=MD5Util.md5_16(password);
			
			if(!acc.getPassword().equals(pwd)){
				rp.setErrcode(2);
				rp.setErrmsg("密码错误！");
				return rp;
			}
			
			accountDao.executeByHql("update Account set lastLoginTime=? where account=?", new Date(), account);
			rp.setErrcode(0);
			rp.setErrmsg("登陆成功！");
			rp.setData(acc);
			session.setAttribute("Account", acc);

		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e);
		}

		return rp;
	}

}
